package fjut.acm.coding.config.async;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;

/**
 * 定义线程池和异步启动
 * 线程池接管项目中的异步方法产生的线程，
 */

@Configuration
/**
 * 异步方法开启注解
 */
@EnableAsync
public class ThreadPoolConfig implements AsyncConfigurer {

    @Value("${cf.config.threadPool.corePoolSize}")
    private int corePoolSize;

    @Value("${cf.config.threadPool.maxPoolSize}")
    private int maxPoolSize;

    @Value("${cf.config.threadPool.queueCapacity}")
    private int queueCapacity;

    /**
     * 定义线程池
     * 如果没有定义线程池的话，每一个都创建一个线程，请求结束销毁线程
     * 大量的创建和销毁浪费资源，启用线程池，合理的重复利用线程。
     * @return
     */
    @Bean
    @Override
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
        taskExecutor.setCorePoolSize(corePoolSize);
        taskExecutor.setMaxPoolSize(maxPoolSize);
        taskExecutor.setQueueCapacity(queueCapacity);
        taskExecutor.setThreadNamePrefix("async-Exec-");
        taskExecutor.initialize();
        return taskExecutor;
    }
}
